<template>
    <div>
        <el-card>
            <el-form :inline="true" :model="queryForm" ref="queryFormRef">
                <el-form-item label="是否展示" prop="status">
                    <el-select v-model="queryForm.status" clearable>
                        <el-option label="展示" :value="1" />
                        <el-option label="不展示" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="位置" prop="type">
                    <el-select v-model="queryForm.type" clearable>
                        <el-option label="首页" :value="1" />
                        <el-option label="点餐页" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="loading" @click="submitForm"
                        v-has="'btn.queryBanner'">查询</el-button>
                    <el-button @click="resetForm(queryFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card>
            <template #header>
                <el-button icon="Plus" @click="handleAdd" v-has="'btn.addBanner'">添加图片</el-button>
            </template>
            <el-table :data="records" style="width: 100%;" v-loading="loading" border>
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column prop="url" label="banner图" min-width="100" align="center">
                    <template #default="{ row }">
                        <el-image :src="row.url"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="position" label="位置" min-width="100" align="center" />
                <el-table-column prop="sort" label="排序" min-width="100" align="center" />
                <el-table-column label="是否展示" min-width="100" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" :loading="switchLoading"
                            @change="handleStatus(row)" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="320" align="center">
                    <template #default="{ row }">
                        <el-button icon="Edit" @click="handleEdit(row)" v-has="'btn.editBanner'">编辑</el-button>
                        <el-button type="danger" icon="Delete" @click="handleDelete(row)"
                            v-has="'btn.deleteBanner'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-pagination v-model:current-page="queryForm.currentPage" v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

        <el-dialog :title="isEdit ? '编辑图片' : '添加图片'" v-model="dialogVisible" :close-on-click-modal="false">
            <AddOrEditBanner v-if="dialogVisible" :is-edit="isEdit" :id="id" @success="onSuccess"></AddOrEditBanner>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="Banner">
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { reactive } from 'vue';
import { bannerChangeStatus, bannerPage, bannerRemove } from '@/api/wx/banner';
import type { BannerPageRequest, BannerType } from '@/api/wx/banner/types';
import  AddOrEditBanner from './components/AddOrEditBanner.vue';

// ---------- 查询 ----------
const loading = ref(false)
const queryForm = reactive<BannerPageRequest>({ currentPage: 1, pageSize: 10 })
const queryFormRef = ref<FormInstance>()
let total = ref(0)
let records = ref<BannerType[]>([])

onMounted(() => {
    submitForm()
})

const submitForm = async () => {
    loading.value = true
    const data = await bannerPage(queryForm);
    if (data.code === 200) {
        records.value = data.data.records
        total.value = data.data.total
    }
    loading.value = false
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const handleSizeChange = (val: number) => {
    queryForm.currentPage = 1
    queryForm.pageSize = val
    submitForm()
}
const handleCurrentChange = (val: number) => {
    queryForm.currentPage = val;
    submitForm()
}

// ---------- 添加/编辑/删除 ----------
const isEdit = ref(false)
const dialogVisible = ref(false)
const id = ref()

const handleAdd = () => {
    dialogVisible.value = true
    isEdit.value = false
}
const handleEdit = (row: BannerType) => {
    dialogVisible.value = true
    isEdit.value = true
    id.value = row.id
}
const handleDelete = async (row: BannerType) => {
    ElMessageBox.confirm(`确认删除图片吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const data = await bannerRemove(row.id as number)
        if (data.code === 200) {
            ElMessage.success('删除成功');
            // 如果删除的是最后一条数据需要回到上一页
            if (records.value.length === 1) {
                queryForm.currentPage -= 1
            }
            submitForm();
        } else {
            ElMessage.error('删除失败');
        }
    });
}
const onSuccess = () => {
    dialogVisible.value = false
    // 如果是新增 需要回到第一页
    if (!isEdit.value) {
        queryForm.currentPage = 1
    }
    submitForm()
}

// ---------- 是否展示 ----------
const switchLoading = ref(false)

const handleStatus = async (row: BannerType) => {
    try {
        switchLoading.value = true
        const data = await bannerChangeStatus(row.id as number, row.status as number)
        if (data.code === 200) {
            ElMessage.success('修改成功');
            submitForm();
        } else {
            ElMessage.error('修改失败');
        }
    } finally {
        switchLoading.value = false
    }
}
</script>

<style scoped lang="scss">
.el-card {
    margin-bottom: 20px;
    min-width: 600px;

    .el-form {

        .el-input {
            width: 240px;
        }

        .el-select {
            width: 240px;
        }

        .el-form-item {
            margin-bottom: 0;
        }
    }
}
</style>